<?php
namespace app\admin\controller;
use think\Controller;

// 管理员配置
class Admin extends Base
{
    // 角色管理
    public function roleList()
    {
        $role = db('auth_group')-> select();
        $rolelist = array();
        foreach ($role as $val){
            $user_group = db('auth_user_group')
                    ->alias('a')
                    ->join('auth_user b','b.id = a.uid','LEFT')
                    ->where('a.group_id',$val['id'])
                    ->where('b.status',1)
                    ->column('b.username');
            $val['user_group'] = implode('，',$user_group);
            $rolelist[] = $val;
        }
        $this->assign('rolelist',$rolelist);
        return $this->fetch();
    }
    
    // 添加、编辑角色
    public function roleAdd()
    {
        $id = input('id') > 0 ? input('id') : 0;
        $role = db('auth_group')->where('id',$id)->find();
        if(!empty($role)){
            $role['rules']=explode(",",$role['rules']);
        }
        $mgroup = db('auth_rule_group')->where('level',1)->where('status',1)->field('name,id')->select();
//        $cgroup = db('auth_rule_group')->where('level',2)->where('status',1)->field('name,id as cid,mid')->select();
        
        /*权限分类三级列表*/
        /*一级列表*/
        $group = array();
        foreach ($mgroup as $val){
            $mgroup = db('auth_rule_group')
                    ->where('mid',$val['id'])
                    ->where('level',2)
                    ->where('status',1)
                    ->field('name,id')
                    ->select();
            /*二级列表*/
            $cgroup=array();
            foreach ($mgroup as $vo){
                $rgroup = db('auth_rule_group')
                        ->where('cid',$vo['id'])
                        ->where('level',3)
                        ->where('status',1)
                        ->field('name,id')
                        ->select();
                 /*三级列表*/
                $g=array();
                foreach ($rgroup as $v){
                    $v['rgroup'] = db('auth_rule')
                            ->where('rulegroup',$v['id'])
                            ->where('status',1)
                            ->field('stitle,id')
                            ->select();
                    $g[]=$v;
                }
                $vo['cgroup'] = $g;
                $cgroup[]=$vo;
                
            }
            $val['mgroup'] = $cgroup;
            $group[]=$val;
        }
        
        if(request()->isPost()){
            $data = [
                'title'=> input('title'),
                'description'=> input('description'),
//                'status' => input('status'),
                'rules' => implode(',',input('rules/a'))
            ];
            $type = $id > 0 ? 2 : 1; // 标识自动验证场景 1:新增 2:编辑更新
            if($type == 2){
                $save = db('auth_group')->where('id',$id)->update($data);
                $data2 = '更新成功';
            } else {
//                unset($data['id']);
                $save = db('auth_group')->insert($data);
                $data2 = '添加成功';
            }
            if($save){
                return json($data2);
            } else {
                $data2 = 404;
                return json($data2,'操作失败',0);
            }
            return;
        }
        
        $this->assign('group',$group);
        $this->assign('role',$role);
        return $this->fetch();
    }
    
    //角色状态变更
    public function roleStatusChg(){
        $id = input('id');
        if ($id < 1){
            return FALSE;
        }
        $data = [
            'status' => input('status')
        ];
        $result = db('auth_group')->where('id',$id)->update($data);
        if ($result) {
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    //删除角色
    public function roleDel(){
        $id = input('id');
        if ($id < 1){
            return json($id);
        }
        $result = db('auth_group')->where('id',$id)->delete();
        if ($result) {
            return json('删除成功!');
        }else{
            return json('删除失败!');
        }
    }
    
    // 权限管理
    public function permissionList()
    {
        $rule = db('auth_rule')
                ->alias('a')
                ->field('a.*,b.name as gname,c.name as mname,d.name as cname')
                ->join('auth_rule_group b','b.id = a.rulegroup','LEFT')
                ->join('auth_rule_group c','c.id = b.mid','LEFT')
                ->join('auth_rule_group d','d.id = b.cid','LEFT')
//                ->order(['mname','cname','gname'])
                ->select();
        $this->assign('rulelist',$rule);
        return $this->fetch();
    }
    
    // 添加、编辑权限
    public function permissionAdd()
    {
        $id = input('id') > 0 ? input('id') : 0;
        $rule = db('auth_rule')->where('id',$id)->find();
        if (!empty($rule)){
            $rgroup=db('auth_rule_group')->where('id',$rule['rulegroup'])->find();
            $rule['mid']=$rgroup['mid'];
            $rule['cname']=db('auth_rule_group')->where('id',$rgroup['cid'])->value('name');
            $rule['gname']=$rgroup['name'];
        }
        $mgroup = db('auth_rule_group')->where('level',1)->where('status',1)->field('name,id')->select();
        
        if(request()->isPost()){
            $data = [
                'name'=> input('name'),
                'title'=> input('title'),
                'stitle'=> input('stitle'),
                'rulegroup'=> input('rulegroup'),
                'status'=> input('status'),
                'is_menu'=> input('is_menu')
            ];
            $type = $id > 0 ? 2 : 1; // 标识自动验证场景 1:新增 2:编辑更新
            if($type == 2){
                $save = db('auth_rule')->where('id',$id)->update($data);
                $data2 = '更新成功';
            } else {
//                unset($data['id']);
                $save = db('auth_rule')->insert($data);
                $data2 = '添加成功';
            }
            if($save){
                return json($data2);
            } else {
                $data2 = 404;
                return json($data2,'操作失败',0);
            }
            return;
        }
        
        $this->assign('mgroup',$mgroup);
        $this->assign('rule',$rule);
        return $this->fetch();
    }
    
    //权限状态变更
    public function permissionStatusChg(){
        $id = input('id');
        if ($id < 1){
            return FALSE;
        }
        $data = [
            'status' => input('status')
        ];
        $result = db('auth_rule')->where('id',$id)->update($data);
        if ($result) {
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    //删除权限
    public function permissionDel(){
        $id = explode(",", input('id'));
        if(empty($id)){
            return json("非法操作！");
        }
        $result = db('auth_rule')->where('id','in',$id)->delete();
        if ($result) {
            return json('删除成功!');
        }else{
            return json('删除失败!');
        }
    }
    
    // 权限分组管理
    public function ruleGroup()
    {
        $rulegroups = db('auth_rule_group')
                ->alias('a')
                ->field('a.*,b.name as mname,c.name as cname')
                ->join('auth_rule_group b','b.id = a.mid','LEFT')
                ->join('auth_rule_group c','c.id = a.cid','LEFT')
                ->order(['cid','mid','sort'])
                ->select();
        $this->assign('rulegroups',$rulegroups);
        return $this->fetch();
    }
    
    // 添加、编辑权限分组
    public function ruleGroupAdd()
    {
        $id = input('id') > 0 ? input('id') : 0;
        $rulegroup = db('auth_rule_group')->where('id',$id)->find();
        $cname = db('auth_rule_group')->where('id',$rulegroup['cid'])->value('name');
        $mgroup = db('auth_rule_group')->where('level',1)->field('name,id')->select();
        
        if(request()->isPost()){
            $data = [
                'name'=> input('name'),
                'mid'=> input('level') == 1 ? 0 : input('mid'),
                'cid'=> input('level') < 3 ? 0 : input('cid'),
                'level'=> input('level'),
                'sort'=> input('sort'),
                'status'=> input('status')
            ];
            if(!!input('icon')){
                $data['icon'] = input('icon');
            }
            $type = $id > 0 ? 2 : 1; // 标识自动验证场景 1:新增 2:编辑更新
            if($type == 2){
                $save = db('auth_rule_group')->where('id',$id)->update($data);
                $data2 = '更新成功';
            } else {
//                unset($data['id']);
                $save = db('auth_rule_group')->insert($data);
                $data2 = '添加成功';
            }
            if($save){
                return json($data2);
            } else {
                $data2 = 404;
                return json($data2,'操作失败',0);
            }
            return;
        }
        
        $this->assign('mgroup',$mgroup);
        $this->assign('cname',$cname);
        $this->assign('rulegroup',$rulegroup);
        return $this->fetch();
    }
    
    //权限分组状态变更
    public function ruleGroupStatusChg(){
        $id = input('id');
        if ($id < 1){
            return FALSE;
        }
        $data = [
            'status' => input('status')
        ];
        $result = db('auth_rule_group')->where('id',$id)->update($data);
        if ($result) {
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    //删除权限分组
    public function ruleGroupDel(){
        $id = explode(",", input('id'));
        if(empty($id)){
            return json("非法操作！");
        }
        $result = db('auth_rule_group')->where('id','in',$id)->delete();
        if ($result) {
            return json('删除成功!');
        }else{
            return json('删除失败!');
        }
    }
    
    //查找下级权限分组-根据id，level
    public function rulegroupChg(){
        $id = input('id');
        $level = db('auth_rule_group')->where('id',$id)->value('level');
        $type= $level == 1 ? 'mid' : ($level== 2 ? 'cid' : 'id');
        $cgroup = db('auth_rule_group')->where($type,$id)->where('level',$level+1)->field('name,id')->select();
     	$html = '<option>——请选择——</option>';
     	foreach ($cgroup as $val){
     		$html .= "<option value='".$val['id']."'>".$val['name']."</option>";
     	}
        $html = !empty($cgroup) ? $html : '<option>暂无此分类，请先添加</option>';
     	return $html;
    }

    // 管理员列表
    public function adminList()
    {
        $adminlist = db('auth_user')
                ->alias('a')
                ->field('a.*,c.title as group_name')
                ->join('auth_user_group b','b.uid=a.id','LEFT')
                ->join('auth_group c','c.id = b.group_id','LEFT')
                ->select();
        $this->assign('adminlist',$adminlist);
        return $this->fetch();
    }
    
    public function adminCheckName($id=0,$name=''){
        if(request()->isPost()){
            $id = input('id');
            $name = input('username');
        }
        $uname = db('auth_user')->column('username');
        $username = db('auth_user')->where('id',$id)->value('username');
        if($username==$name){
            return true;
        }elseif(in_array($name,$uname)){
            return json('注册名称已使用，请更换！');
        }
        return true;
    }

        // 添加、编辑管理员
    public function adminAdd()
    {
        $id = input('id') > 0 ? input('id') : 0;
        $admin = db('auth_user')
                ->where('id',$id)
                ->alias('a')
                ->field('a.*,b.group_id')
                ->join('auth_user_group b','b.uid=a.id','LEFT')
                ->find();
        $group = db('auth_group')->where('status',1)->field('title,id')->select();
        
        if(request()->isPost()){
            $this->adminCheckName($id,input('username'));
            $data = [
                'username'=> input('username'),
                'status'=> input('status')
            ];
            if(md5('******') != input('password')){
                $code = mt_rand(100, 10000);
                $data['code'] = $code;
                $data['password'] = md5(input('password').$code);
            } elseif($id == 0) {
                return '该密码不可用，请更换！';
            }
            $type = $id > 0 ? 2 : 1; // 标识自动验证场景 1:新增 2:编辑更新
            if($type == 1){
//                unset($data['id']);
                $data['create_time'] = time();
                $save = $id = db('auth_user')->insertGetId($data);
                $data2 = '添加成功';
            } elseif ($data == array_intersect($data, $admin)){
                $save = true;
                $data2 = '更新成功';
            } else {
                $save = db('auth_user')->where('id',$id)->update($data);
                $data2 = '更新成功';
            }
                /*判断是否已分组*/
            if($save){
                $groupid=db('auth_user_group')->where('uid',$id)->value('group_id');
                if(!($groupid>0)){
                    $data1 = [
                        'uid' => $id,
                        'group_id' => input('group_id')
                    ];
                    $save1 = db('auth_user_group')->insert($data1);
                }elseif ($groupid!=input('group_id')) {
                    $data1 = ['group_id' => input('group_id')];
                    $save1 = db('auth_user_group')->where('uid',$id)->update($data1);                    
                }
                return json($data2);
            } else {
                $data2 = 404;
                return json($data2,'操作失败',0);
            }
            return;
        }
        
        $this->assign('group',$group);
        $this->assign('admin',$admin);
        return $this->fetch();
    }
    
    //管理员状态变更
    public function adminStatusChg(){
        $id = input('id');
        if ($id < 1){
            return FALSE;
        }
        $data = [
            'status' => input('status')
        ];
        $result = db('auth_user')->where('id',$id)->update($data);
        if ($result) {
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    //删除管理员
    public function adminDel(){
        $id = explode(",", input('id'));
        if(empty($id)){
            return json("非法操作！");
        }
        $r = db('auth_user_group')->where('uid','in',$id)->delete();
        $result = db('auth_user')->where('id','in',$id)->delete();
        if ($r && $result) {
            return json('删除成功!');
        }else{
            return json('删除失败!');
        }
    }
    
}
